package com.klhappy.houyuan.fragement;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.klhappy.houyuan.R;
import com.klhappy.houyuan.activity.XiangqingActivity;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.bean.GoodsAllBean;
import com.klhappy.houyuan.bean.LanziBean.LanZiBean;
import com.klhappy.houyuan.bean.LanziBean.Records;
import com.klhappy.houyuan.bean.LanziBean.Total;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.dialog.NetWorkDialog;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.activity.ConfirmOrderActivity;
import com.klhappy.houyuan.modle.LanZiModle;
import com.klhappy.houyuan.utils.NotifyMethod;
import com.klhappy.houyuan.view.RoundImageView;
import com.klhappy.houyuan.view.swipemenulistview.SwipeMenu;
import com.klhappy.houyuan.view.swipemenulistview.SwipeMenuCreator;
import com.klhappy.houyuan.view.swipemenulistview.SwipeMenuItem;
import com.klhappy.houyuan.view.swipemenulistview.SwipeMenuListView;
import com.klhappy.houyuan.view.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.klhappy.houyuan.utils.JsonCode;
import com.klhappy.houyuan.view.AbsFragment;
import com.klhappy.houyuan.view.ImageManager;

import java.util.ArrayList;
import java.util.List;

public class Lanzi_Fragment extends AbsFragment implements CallBackInterModle {
    public static final String MV = "Lanzi_Fragment";
    @InjectView(R.id.lv_lanzi)
    SwipeMenuListView mListView;
    @InjectView(R.id.tv_sumfee)
    TextView tv_sumfee;
    @InjectView(R.id.tv_num)
    TextView tv_num;
    @InjectView(R.id.cb_all)
    CheckBox cb_all;
    @InjectView(R.id.list_no_data)
    LinearLayout list_no_data;
    @InjectView(R.id.bt_look)
    Button bt_look;

    @OnClick(R.id.bt_look)
    public void bt_look() {
        getActivity().startActivity(new Intent(getActivity(), Houyuan_Fragment.class));
    }

    @OnClick(R.id.ll_next)
    public void ll_next() {
        itemList = new ArrayList<>();
        try {
            for (int i = 0; i < mChecked.size(); i++) {
                if (mChecked.get(i)) {
                    itemList.add(new GoodsAllBean(nowGoods.get(i).getGoods_id(), nowGoods.get(i).getG_icon()
                            , nowGoods.get(i).getG_name()
                            , nowGoods.get(i).getG_price() + ""
                            , nowGoods.get(i).getG_unit()
                            , nowGoods.get(i).getGoods_number() + "", ""));
                }
            }
            Intent intent = new Intent(getActivity(), ConfirmOrderActivity.class);
            intent.putExtra("goods", itemList);
            startActivity(intent);
        } catch (Exception e) {
            Log.e("this", "looger:" + e);
        }
    }

    private LanZiAdapter mAdapter;
    private LanZiModle ziModle;
    private LanZiBean ziBean;
    private List<Records> lanziBeans = null;
    private List<Records> nowGoods;
    private List<Boolean> mChecked;
    private List<Total> total;
    private NetWorkDialog dialog;
    private float price;
    private float num;
    private static boolean isCheck = true;
    private ArrayList<GoodsAllBean> itemList;
    private Message msg = new Message();

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            float totalall = Float.parseFloat(tv_sumfee.getText().toString());
            int all = Integer.parseInt(tv_num.getText().toString());
            switch (msg.what) {
                case 1:
//					cb_all.setChecked(true);
                    price = (float) msg.obj;
                    tv_sumfee.setText("" + (totalall + price));
                    tv_num.setText((all + 1) + "");
                    mAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    cb_all.setChecked(false);
                    price = (float) msg.obj;
                    tv_sumfee.setText("" + (totalall - price));
                    tv_num.setText((all - 1) + "");
                    mAdapter.notifyDataSetChanged();
                    break;
                case 3:
                    if (isCheck) {
                        num = (float) msg.obj;
                        tv_sumfee.setText("" + (totalall + num));
                    }
                    break;
                case 4:
                    if (isCheck) {
                        num = (float) msg.obj;
                        tv_sumfee.setText("" + (totalall + num));
                    }
                    break;
                case 5:
                    tv_sumfee.setText(total.get(0).getTotal() + "");
                    tv_num.setText(lanziBeans.size() + "");
                    break;
                case 6:
                    tv_sumfee.setText("0");
                    tv_num.setText("0");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg2, container, false);
        ButterKnife.inject(this, view);

        showDialog("请稍等...");
        ziModle = new LanZiModle(getActivity());
        ziModle.setCallBackInterModle(this);
        dialog = new NetWorkDialog(getActivity());
        setSwipeMenu();

        cb_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;
                if (cb.isChecked()) {
                    mAdapter.notfiy(true);
                } else {
                    mAdapter.notfiy(false);
                }
            }
        });

        NotifyMethod.getInstance().addObserver(MV, new NotifyMethod.NotifyListener() {
            @Override
            public void notify(Object o) {
                ziModle.getGoods();
            }
        });

        ziModle.getGoods();
        return view;
    }

    private void setSwipeMenu() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem openItem = new SwipeMenuItem(getActivity());
                openItem.setBackground(new ColorDrawable(Color.rgb(0x86, 0x9e, 0x34)));
                openItem.setWidth(dp2px(68));
                openItem.setTitle("删除");
                openItem.setTitleSize(18);
                openItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(openItem);
            }
        };
        mListView.setMenuCreator(creator);

        mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        ziModle.setGoods(lanziBeans.get(position).getId());
                        lanziBeans.remove(position);
                        showDialog("请稍等...");
                        break;
                    default:
                        break;
                }
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), XiangqingActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("goodId", lanziBeans.get(position).getGoods_id() + "");
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.GOODS_LANZI_URL)) {
            closeDialog();
            if (o.getCode() == 200) {
                if (o.toString() != null) {
                    ziBean = JsonCode.getClass(o.getEntity(), LanZiBean.class);
                    lanziBeans = JsonCode.getClassList(ziBean.getRecords(), Records.class);
                    total = JsonCode.getClassList(ziBean.getTotal(), Total.class);
                    mAdapter = new LanZiAdapter(getActivity(), lanziBeans, handler);
                    mListView.setAdapter(mAdapter);
                    tv_sumfee.setText(total.get(0).getTotal() + "");
                    tv_num.setText(lanziBeans.size() + "");

                    if (lanziBeans == null) {
                        list_no_data.setVisibility(View.VISIBLE);
                    } else {
                        if (lanziBeans.size() == 0) {
                            list_no_data.setVisibility(View.VISIBLE);
                        } else {
                            list_no_data.setVisibility(View.GONE);
                        }
                    }
                }
            } else {
                dialog.netWork(o.getMsg());
                dialog.show();
            }
        } else if (url.equals(UrlConstant.REMOVEGOODS_URL)) {
            closeDialog();
            if (o.getCode() == 200) {
                mAdapter.notifyDataSetChanged();
                ziModle.getGoods();
            } else {
                showToast(o.getMsg());
            }
        }
    }

    public class LanZiAdapter extends BaseAdapter {
        private List<Records> mGoodsItemList;
        private Context mContext;
        private Handler handler;
        private int number;
        private float itemPrice;
        public int i = 0;

        public LanZiAdapter(Context context, List<Records> goodsItemList, Handler handler) {
            this.mGoodsItemList = goodsItemList;
            this.mContext = context;
            this.handler = handler;

            mChecked = new ArrayList<>();
            nowGoods = new ArrayList<>();
            for (int i = 0; i < mGoodsItemList.size(); i++) {
                mChecked.add(true);
            }
            nowGoods = mGoodsItemList;
        }

        public void notfiy(boolean isCheck) {
            mChecked.clear();
            if (isCheck) {
                msg.what = 5;
                handler.handleMessage(msg);
            } else {
                msg.what = 6;
                handler.handleMessage(msg);
            }
            for (int i = 0; i < mGoodsItemList.size(); i++) {
                mChecked.add(isCheck);
            }
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mGoodsItemList.size();
        }

        @Override
        public Object getItem(int position) {
            return mGoodsItemList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.lanzi_item, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final float price = mGoodsItemList.get(position).getG_price();
            int count = mGoodsItemList.get(position).getGoods_number();

            ImageManager.loadImage(UrlConstant.BASE_URL + mGoodsItemList.get(position).getG_icon(), holder.ivImage);
            holder.tvDes.setText(mGoodsItemList.get(position).getG_name());
            holder.tvPrice.setText("￥" + price + "元/" + mGoodsItemList.get(position).getG_unit());
            holder.tvSum.setText("" + (price * count));
            holder.etCount.setText("" + count);
            holder.cb_del.setChecked(mChecked.get(position));

            holder.cb_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemPrice = Float.parseFloat(holder.tvSum.getText().toString());
                    CheckBox cb = (CheckBox) v;
                    mChecked.set(position, cb.isChecked());
                    if (cb.isChecked()) {
                        isCheck = true;
                        msg.what = 1;
                        msg.obj = itemPrice;
                        handler.handleMessage(msg);
                    } else {
                        isCheck = false;
                        msg.what = 2;
                        msg.obj = itemPrice;
                        handler.handleMessage(msg);
                    }
                }
            });

            holder.ib_increase.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    i = 0;
                    number = Integer.parseInt(holder.etCount.getText().toString());
                    number++;
                    i++;
                    nowGoods.get(position).setGoods_number(nowGoods.get(position).getGoods_number() + 1);
                    holder.etCount.setText("" + number);
                    holder.tvSum.setText("" + (price * number));
                    float num = i * price;
                    msg.what = 3;
                    msg.obj = num;
                    handler.handleMessage(msg);
                }
            });
            holder.ib_decrease.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    i = 0;
                    number = Integer.parseInt(holder.etCount.getText().toString());
                    if (number > 1) {
                        number--;
                        i--;
                        nowGoods.get(position).setGoods_number(nowGoods.get(position).getGoods_number() - 1);
                        holder.etCount.setText("" + number);
                        holder.tvSum.setText("" + (price * number));
                        float num = i * price;
                        msg.what = 4;
                        msg.obj = num;
                        handler.handleMessage(msg);
                    }
                }
            });
            return convertView;
        }

        class ViewHolder {
            @InjectView(R.id.iv_image)
            ImageView ivImage;
            @InjectView(R.id.tv_des)
            TextView tvDes;
            @InjectView(R.id.tv_price)
            TextView tvPrice;
            @InjectView(R.id.tv_sum)
            TextView tvSum;
            @InjectView(R.id.et_count)
            EditText etCount;
            @InjectView(R.id.cb_del)
            CheckBox cb_del;
            @InjectView(R.id.ib_increase)
            RoundImageView ib_increase;
            @InjectView(R.id.ib_decrease)
            RoundImageView ib_decrease;
            @InjectView(R.id.ll_dian)
            LinearLayout ll_dian;

            public ViewHolder(View view) {
                ButterKnife.inject(this, view);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        NotifyMethod.getInstance().removeObserver(MV);
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }
}
